package com.cheneyjoo.servlets;

import com.alibaba.fastjson.JSONObject;
import com.cheneyjoo.controller.StudentController;
import com.cheneyjoo.model.STUDENT;
import com.cheneyjoo.tools.AjaxJsonDataHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Optional;

@WebServlet(name = "DeleteStudentServlet", urlPatterns = "/deletestudent")
public class DeleteStudentServlet extends HttpServlet {
    private static final long serialVersionUID = 4941810699877323786L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        JSONObject jsonObject = AjaxJsonDataHelper.getJsonObject(request);
        String id=jsonObject.get("id").toString();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        STUDENT student= null;
        PrintWriter out = response.getWriter();
        JSONObject result=new JSONObject();
        try {
            StudentController sc=new StudentController();
            List<STUDENT> studentList = sc.checkStudentHaveClass(id);
            if (Optional.ofNullable(studentList).isPresent()){
                StringBuilder msg=new StringBuilder();
                studentList.stream().forEach(s->{
                    msg.append(s.getStudent_name()+"尚未移出班级，不能删除！\n");
                });
                result.put("error",2);
                result.put("msg","失败,"+msg);
            }else{
                boolean b = sc.deleteStudent(id);
                if (b){
                    result.put("error",1);
                    result.put("msg","成功");
                }else {
                    result.put("error",0);
                    result.put("msg","失败");
                }
            }
            out.print(result);
        } catch (Exception e) {
            result.put("error",-1);
            result.put("msg","失败");
            out.print(result);
        }finally {
            out.close();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
